﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;

namespace RH
{
    public partial class wfLiquidacionMnt : EditPage
    {
        public const int _GRDLIST_STANULADO = 6;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                switch (this.Request.Params["__EVENTTARGET"])
                {
                    case "TiempoServicio":
                        this.TiempoServicio();
                        break;
                    case "CalCTSVacaGratiTruncas":
                        this.CalCTSVacaGratiTruncas();
                        break;
                }

                this.LoadInPostBack();
                return;
            }
            this.LoadData();
        }

        public override void LoadInPostBack()
        {
            this.RegisterGeneralScripts();
        }

        public override void LoadInitialSettings()
        {
            this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
            this.SetInitialTitle("Liquidacion");
        }

        public override void LoadListControls()
        {
            ETablaGenDet objEDet = new ETablaGenDet();
            MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
            objEDet.IdTabla = ConstMultitabla.FORMA_PAGO;
            DataTable dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidForPago, dt, "dsDescrip", "idCodigo", true, false);

            objEDet.IdTabla = ConstMultitabla.MOTIVO_CESE;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidMotivoCese, dt, "dsDescrip", "idCodigo", true, false);

        }

        public override void DataToControls()
        {

        }

        public override void RegisterGeneralScripts()
        {
            this.txtidLiquidacion.Attributes.Add("readonly", "true");
            this.txtdsTiempoServ.Attributes.Add("readonly", "true");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtidPersonal.ClientID + "','Ingrese el Personal');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtfeCese.ClientID + "','Ingrese la fecha de cese');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("var varRet = modalDialog('wfPeriodoPlani.aspx?IdPersonal=' + document.getElementById('" + this.hdnidPersonal.ClientID + "').value + '&IdForPago='+ document.getElementById('" + this.ddlidForPago.ClientID + "').value + '&IdPlaniFilter=016,017,018,019',750,400);");
            sb.AppendLine("if(varRet==null)");
            sb.AppendLine("return false;");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnidPlanilla.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[2];");
            sb.AppendLine("ctl = document.getElementById('" + this.txtidPlanilla.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[3];");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnnuProcAnual.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[4];");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnidMes.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[5];");
            sb.AppendLine("__doPostBack('CalCTSVacaGratiTruncas', '');  ");

            this.txtidPlanilla.OnClientClick = sb.ToString();

            sb = new StringBuilder();
            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtidPersonal.ClientID + "','Seleccione el Personal');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("{document.getElementById('" + this.txtfeCese.ClientID + "').value = '';");
            sb.AppendLine("return !varRpta;}");
            sb.AppendLine("__doPostBack('TiempoServicio', '');  ");

            this.txtfeCese.OnClientClickDay = sb.ToString();

            sb = new StringBuilder();

            sb.AppendLine("var varRet = modalDialog('wfPersonal.aspx',750,400);");
            sb.AppendLine("if(varRet==null)");
            sb.AppendLine("return false;");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnidPersonal.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[0];");
            sb.AppendLine("ctl = document.getElementById('" + this.txtidPersonal.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[1];");
            sb.AppendLine("ctl = document.getElementById('" + this.txtfeIngreso.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[6];");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnidOcupacion.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[7];");
            sb.AppendLine("ctl = document.getElementById('" + this.txtidOcupacion.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[8];");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnnuSecuenContra.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[9];");
            this.txtidPersonal.OnClientClick = sb.ToString();

            sb = new StringBuilder();

            sb.AppendLine("function validateEditForm(key){");
            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtidPersonal.ClientID + "','Ingrese el Personal');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
        }

        public void RegisterEditPopupScripts()
        {

            this.txtidConRemu.Attributes.Add("readonly", "true");
            this.txtdsConRemu.Attributes.Add("readonly", "true");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
            //sb.AppendLine("varRpta = isEmptyControl('" + this.PddlidTipoCance.ClientID + "','Ingrese el tipo de Cancelacion.');");
            //sb.AppendLine("if(varRpta==true)");
            //sb.AppendLine("return !varRpta;");
            //sb.AppendLine("varRpta = isEmptyControl('" + this.PtxtmtCuota.ClientID + "','Ingrese el monto de la cuota.');");
            //sb.AppendLine("if(varRpta==true)");
            //sb.AppendLine("return !varRpta;");
            sb.AppendLine("return true;}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);

            this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
            this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";

        }

        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_SAVE:
                case ConstMenuToolbarValue.BUTTON_SAVENEW:
                    if (this.FormEditAction != FormEditAction.Delete)
                        this.SaveData(e.Item.Value);
                    else
                        this.DeleteData();
                    break;
                case ConstMenuToolbarValue.BUTTON_EXIT:
                    this.Response.Redirect("wfLiquidacionBnd.aspx?Filter=1");
                    break;
            }
        }

        protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_CALCULAR:
                    this.RegisterEditPopupScripts();
                    //this.hdnstCalcular.Value = ConstFlagEstado.DESACTIVADO;
                    //this.hdnstNuProceCal.Value = ConstFlagEstado.DESACTIVADO;
                    break;
            }

        }

        protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

            switch (e.CommandName)
            {
                case ConstGridRowCommand.GRIDEDIT:
                    this.lblTitlePopup.Text = "Liquidacion (Editar Concepto)";
                    this.GridEditAction = GridEditAction.Edit;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;
            }
        }

        protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                String strRI = e.Row.RowIndex.ToString();
                ImageButton bttedit = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDEDIT);
                bttedit.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDEDIT + "','" + strRI + "');";

                if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
                {
                    e.Row.ForeColor = System.Drawing.Color.Red;
                    bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                }
            }

        }

        protected void bttOkPopup_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)this.DataSource;
            DataRow dr = null;


            dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);

            if (this.GridEditAction != GridEditAction.Delete)
            {
                dr["nuMes"] = int.Parse(this.txtnuMes.Text);
                dr["nuDias"] = int.Parse(this.txtnuDias.Text);
            }

            this.GridSetDataBinding(grdList, dt);
        }

        public override void LoadDataEditPopup(GridView grid, int rowIndex)
        {
            this.ClearEditPopup();

            DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, rowIndex);

            if (dr == null)
                return;

            WebHelper.RowToControl(dr, "idConRemu", this.txtidConRemu);
            WebHelper.RowToControl(dr, "dsConRemu", this.txtdsConRemu);
            WebHelper.RowToControl(dr, "nuMes", this.txtnuMes);
            WebHelper.RowToControl(dr, "nuDias", this.txtnuDias);
        }

        public new void ClearEditPopup()
        {
            //this.hdnidForPagoPp.Value = "";
            //this.hdnidPlanillaPp.Value = "";
            this.txtidConRemu.Text = "";
            this.txtdsConRemu.Text = "";
            this.txtnuMes.Text = "";
            this.txtnuDias.Text = "";

        }

        public override void SaveData(String key)
        {
            if (this.ValidateData() == false)
                return;

            IEntityBase objE = (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Liquidacion));

            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            {

                case FormEditAction.AddNew:
                case FormEditAction.Copy:
                    strMsg = "Se ha registrado La Liquidacion : " + strRet[0].ToString();
                    break;
                default:
                    strMsg = "Se ha modificado La Liquidacion : " + this.txtidLiquidacion.Text;
                    break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfLiquidacionMnt.aspx?Filter=1");
        }

        public override void DeleteData()
        {
            IEntityBase objE = (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));
            objPro.DeleteData(objE);

            //this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Se anulo el derechohabiente  : " + txtidPersonal.Text, "wfPerDereHabiBnd.aspx?Filter=1");

        }

        public override Object CreateEntitySet()
        {
            ELiquidacion objE = new ELiquidacion();

            if (this.FormEditAction == FormEditAction.AddNew || this.FormEditAction == FormEditAction.Copy)
                objE.EntityState = EntityState.Added;
            else
            {
                IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Liquidacion));
                objE.IdLiquidacion = this.txtidLiquidacion.Text;
                objE = (ELiquidacion)objBO.GetByKey(objE);

                if (this.FormEditAction == FormEditAction.Edit)
                    objE.EntityState = EntityState.Modified;
                if (this.FormEditAction == FormEditAction.Delete)
                    objE.EntityState = EntityState.Deleted;

            }

            objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            WebHelper.ControlToEntity(ddlidForPago, objE, "IdForPago");
            WebHelper.ControlToEntity(hdnidPlanilla, objE, "IdPlanilla");
            WebHelper.ControlToEntity(hdnnuProcAnual, objE, "NuProcAnual");
            WebHelper.ControlToEntity(hdnidPersonal, objE, "IdPersonal");
            WebHelper.ControlToEntity(txtidLiquidacion, objE, "IdLiquidacion");
            WebHelper.ControlToEntity(hdnnuSecuenContra, objE, "NuSecuenContra");
            WebHelper.ControlToEntity(txtfeIngreso, objE, "FeIngreso");
            WebHelper.ControlToEntity(txtfeCese, objE, "FeCese");
            WebHelper.ControlToEntity(hdnidOcupacion, objE, "IdCargo");
            WebHelper.ControlToEntity(ddlidMotivoCese, objE, "IdMotivoCese");
            WebHelper.ControlToEntity(txtmtAPagar, objE, "MtAPagar");
            WebHelper.ControlToEntity(txtdsobserva, objE, "DsObserva");
            WebHelper.ControlToEntity(hdnidMes, objE, "IdMes");
            
            if (this.FormEditAction != FormEditAction.Delete)
            {
                objE.StAnulado = ConstFlagEstado.DESACTIVADO;
            }
            else
            {
                objE.StAnulado = ConstFlagEstado.ACTIVADO;
            }
            
            DataTable dt = (DataTable)this.DataSource;

            this.ClearDeletedRow(this.DataSource, "stAnulado");
            IList<ELiquidacionDet> colELiqui = new List<ELiquidacionDet>();

            if (this.FormEditAction == FormEditAction.Delete)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    this.MarkDeletedRow(dr, "stAnulado");
                }
            }


            foreach (DataRow dr in dt.Rows)
            {
                ELiquidacionDet ObjEDet = new ELiquidacionDet();

                ObjEDet.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                ObjEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();

                WebHelper.ControlToEntity(ddlidForPago, ObjEDet, "IdForPago");
                WebHelper.ControlToEntity(hdnidPlanilla, ObjEDet, "IdPlanilla");
                WebHelper.ControlToEntity(hdnnuProcAnual, ObjEDet, "NuProcAnual");
                WebHelper.ControlToEntity(hdnidPersonal, ObjEDet, "IdPersonal");
                WebHelper.ControlToEntity(txtidLiquidacion, ObjEDet, "IdLiquidacion");
                ObjEDet.NuSecuen = int.Parse(dr["nuSecuen"].ToString());
                ObjEDet.IdConRemu = dr["idConRemu"].ToString();
                ObjEDet.NuMes = int.Parse(dr["nuMes"].ToString());
                ObjEDet.NuDia = int.Parse(dr["nuDias"].ToString());

                if (this.FormEditAction != FormEditAction.Delete)
                {
                    ObjEDet.StEditado = ConstFlagEstado.DESACTIVADO;
                }
                else 
                {
                    ObjEDet.StEditado = ConstFlagEstado.ACTIVADO;
                }

                ObjEDet.EntityState = EntityState.Added;

                colELiqui.Add(ObjEDet);

            }


            ELiquidacionSet objESet = new ELiquidacionSet();
            objESet.Liquidacion = objE;
            objESet.LiquidacionDet = colELiqui;

            return objESet;
        }

        public override void LockControls()
        {
            if (this.FormEditAction != FormEditAction.AddNew)
            {
                //this.txtmtprestamo.Enabled = false;
                this.txtidPersonal.EnabledButton = false;
                this.txtidPlanilla.EnabledButton = false;
                //this.txtfePrestamo.Enabled = false;
                //this.ddlidMoneda.Enabled = false; 
            }
        }

        public void TiempoServicio()
        {
            DateTime dtmFeIngreso = DateTime.Parse(txtfeIngreso.Text);
            DateTime dtmFeCese = DateTime.Parse(txtfeCese.Text);
            int day = 0;
            int month = 0;
            int year = 0;

            if (dtmFeCese.Day < dtmFeIngreso.Day)
            {
                day = dtmFeCese.Day + 30 - dtmFeIngreso.Day;
                if (dtmFeCese.Month - 1 < dtmFeIngreso.Month)
                {
                    month = dtmFeCese.Month + 12 - dtmFeIngreso.Month;
                    year = dtmFeCese.Year - 1 - dtmFeIngreso.Year;
                }
                else
                {
                    month = dtmFeCese.Month - dtmFeIngreso.Month;
                    year = dtmFeCese.Year - dtmFeIngreso.Year;
                }

            }
            else
            {
                day = dtmFeCese.Day - dtmFeIngreso.Day;
                if (dtmFeCese.Month < dtmFeIngreso.Month)
                {
                    month = dtmFeCese.Month + 12 - dtmFeIngreso.Month;
                    year = dtmFeCese.Year - 1 - dtmFeIngreso.Year;
                }
                else
                {
                    month = dtmFeCese.Month - dtmFeIngreso.Month;
                    year = dtmFeCese.Year - dtmFeIngreso.Year;
                }
            }

            this.txtdsTiempoServ.Text = year.ToString() + (year == 1 ? " año  " : " años  ") + month.ToString() + (month == 1 ? " mes  " : " meses  ") + day.ToString() + (day == 1 ? " dia  " : " dias  ");
        }

        public void CalCTSVacaGratiTruncas()
        {
            ELiquidacionBandeja objE = new ELiquidacionBandeja();
            RHBOQry.ILiquidacion objBOI = (RHBOQry.ILiquidacion)WCFHelper.GetObject<RHBOQry.ILiquidacion>(typeof(RHBOQry.Liquidacion));
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objE.IdPlanilla = hdnidPlanilla.Value;
            objE.FeIngreso = DateTime.Parse(txtfeIngreso.Text);
            objE.FeCese = DateTime.Parse(txtfeCese.Text);
            DataTable dt = objBOI.GetCTSVacaGratiTruncas(objE);

            this.GridSetDataBinding(grdList, dt);

        }

        public void CalcularLiquidacion()
        {



        }
    }
}